import { Button, GetProps, Input, Popconfirm, Table, type TableColumnsType } from 'antd';
import { GFS } from "@/hooks/useAssignGlobalProps";
import { useEffect, useRef, useState } from 'react';
import { AddMenuModal } from './AddMenuModal';
import { deleteMenu, getMenuList } from '@/interfaces';
import { SyncOutlined } from '@ant-design/icons';

type SearchProps = GetProps<typeof Input.Search>;
export interface MenuDataType {
  key: React.Key;
  id: number;
  label: string;
  path: string;
  isFolder: boolean;
  icon: string;
  parentId: number;
  sort: number;
  createdBy: number;
  children?: MenuDataType[]
}
export default function MenuManager(){
  const ref = useRef(null);
  const [dataSource, setDataSource] = useState<MenuDataType[]>([]);
  const [openStateObj, setOpenStateObj] = useState<Record<string, boolean>>({});
  const [parentNode, setParentNode] = useState<MenuDataType|null>(null)

  const [editObj, setEditObj] = useState<MenuDataType|null>(null);

  const columns: TableColumnsType<MenuDataType> = [
    {
      title: '页面名称',
      dataIndex: 'label',
    },
    {
      title: '路径',
      dataIndex: 'path',
    },
    {
      title: '图标',
      dataIndex: 'icon',
    },
    {
      title: '是否文件夹',
      dataIndex: 'isFolder',
      render: (_, record) => (
        record.isFolder ? "是" : "否"
      )
    },
    {
      title: '排序',
      dataIndex: 'sort',
    },
    // {
    //   title: '创建者',
    //   dataIndex: 'createdBy',
    // },
    {
      title: "操作",
      width: 180,
      align: "center",
      render: (_, record) => (
        <div>
          <Popconfirm
            title="删除页面"
            description={deleteDesc(record)}
            onConfirm={() => delCurMenu(record)}
          >
            <Button type="text" size="small" danger>删除</Button>
          </Popconfirm>
          <Button color="primary" variant="text" size="small" onClick={()=>goToEdit(record)}> 编辑 </Button>
        </div>
      ),
    },
  ];
  function deleteDesc(record: MenuDataType){
    const state =  Array.isArray(record.children) && record.children.length > 0
    return `确认删除该菜单${state?"以及子菜单":""}吗？`
  }
  async function delCurMenu(record: MenuDataType) {
    try {
      const res = await deleteMenu(record.id);

      if (res.status === 201 || res.status === 200) {
        GFS.message.success(res.data.message);
        freshPage();
      }
    } catch (e: any) {
      GFS.message.error(e.response?.data?.message || "系统繁忙，请稍后再试");
    }
  }
  async function goToEdit(record: MenuDataType){
    // const {parentId} = record
    // if(parentId>0){
    //   setParentNode(getPNode(dataSource, parentId))
    // }else{
    //   setParentNode(null)
    // }
    setEditObj(record)
    setIsOpen(true)

    // function getPNode(data: MenuDataType[], id: number): MenuDataType|null{
    //   if(data.length===0)return null
    //   for(let i=0;i<data.length;i++){
    //     const item = data[i]
    //     if(item.id === id){
    //       return item
    //     }else{
    //       const res = getPNode(item.children || [], id)
    //       if(res)return res
    //     }
    //   }
    //   return null
    // }
  }
  
  async function getData(filter: string=''){
    const res = await getMenuList(1, 1000, filter, "path,label");
    const {data} = res.data
    setDataSource(data.map((item: MenuDataType)=>{
      setOpenStateObj({...openStateObj,[item.path]: false})
      return item
    }))
  }
  useEffect(()=>{
    getData()
  },[])

  function freshPage(){
    getData()
  }
  const onSearch: SearchProps['onSearch'] = (value, _e, info) => {
    getData(value)
  }
  const [isOpen, setIsOpen] = useState(false);
  return (
    <div className="flex flex-col gap-3 bg-white h-full p-4">
      <header className='flex justify-between'>
        <div className='flex-1 w-10 flex gap-3'>
          <Input.Search placeholder="输入页面/路径查询" onSearch={onSearch} style={{ width: 200 }} allowClear/>
          <Button type='primary' onClick={()=>{setIsOpen(true);setEditObj(null)}}>新增</Button>
        </div>
        <div>
          <Button shape="circle" icon={<SyncOutlined />} onClick={freshPage}/>
        </div>
      </header>
      <main ref={ref} className='flex-1 h-20 overflow-y-auto'>
        <Table<MenuDataType>
          size="middle"
          columns={columns}
          dataSource={dataSource}
          bordered
          pagination={false}
        />
      </main>
      <AddMenuModal isOpen={isOpen} handleClose={()=>setIsOpen(false)} freshPage={freshPage} editObj={editObj}
        dataSource={dataSource}/>
    </div>
  )
}